package controllers;


	import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observer;

import model.FinanceSystemModel;
import client.CliMessage;
import client.SGI;


			/**
			 * This Class is a Finance System Controller which extends AbstractController
			 * @author Tal 
			 *
			 */

			public class FinanceSystemController extends AbstractController
			{	
						private FinanceSystemModel finSystemModel;
						private Observer prevObserver;
						private double price;
						private int pid;
						private int serviceId;
						/**
						 * This is Finance System Controller constructor.
						 * @param finSystemModel is Finance System Model instance.
						 */
						public FinanceSystemController(FinanceSystemModel finSystemModel, Observer observer) 
						{
							super(null,finSystemModel);
							this.finSystemModel = finSystemModel;
							this.prevObserver=observer;
							
							///get taarif 
							    getCurrTaarif();
						}
						
					
						public void getCurrTaarif()
						{
							int serviceId=finSystemModel.getGID();
							
							//get the cuurent taarif 
							String searchQuery = "search"	+"SELECT * "
			                                                +" FROM taarif AS t "
									                        +" WHERE t.serviceid=" + serviceId  + "";
	                                       sendToServer(searchQuery);
										
						}
						
						public void chargeCustomerByService()
						{
							//if registerd customer-buy photo or sample
							if(finSystemModel.getServiceByName(finSystemModel.getGID()).equals("Buy Photo") || finSystemModel.getServiceByName(finSystemModel.getGID()).equals("Buy Sample"))
							{
								System.out.println("customer charge..............");
								
								if(finSystemModel.getServiceByName(finSystemModel.getGID()).equals("Buy Photo"))
								    serviceId=1;
								else//sample
									serviceId=3;
								
								//insert to Payment method
								String creditN = finSystemModel.getCreditN();
								String ccv = String.valueOf(finSystemModel.getCCV());
								String Expire=finSystemModel.getExpire();
								String type=finSystemModel.getType();
							
								
								String insertQuery = "adu"	+"INSERT INTO payment_method "
				                                         	+"(creditnum,ccv,expire,type) VALUES "
				                                          	+"('" + creditN + "','" + ccv + "','" + Expire + "','" + type + "'"+")";
								
								
								
								    sendToServer(insertQuery);
			
			                        //get the last pid that insert
			                         String searchQuery= "search" +"SELECT p.pid"
					                                              + " FROM payment_method AS p "
					                                              + " ORDER BY p.pid DESC "
			                                                      + " LIMIT 1";
			                          sendToServer(searchQuery);
			
								
								
								
							}//subscribed customer
							else
							{
								System.out.println("subscribed charge..............");
								
								//insert to user_groups
								int uid = finSystemModel.getUID();
								int gid = finSystemModel.getGID();
							    int pid =finSystemModel.getPID();
								 
								String insertQuery2 = "adu"	+"INSERT INTO user_groups "
									                    	+"(uid,gid) VALUES "
									                    	+"(" + uid + "," + gid + ")";
								
								
								 sendToServer(insertQuery2);
								
							
								
								 int balance=0;
								 double balance_value=price;
								 
								 ///check for photo packege subscription
								if(finSystemModel.getServiceByName(finSystemModel.getGID()).equals("Photo Package"))
									balance=200;
								else
								if(finSystemModel.getServiceByName(finSystemModel.getGID()).equals("Daily Photo"))
									balance=finSystemModel.getArea();//area
								else
									balance=1;
								
					             int active=1;
								 System.out.println("finance pid::::::"+pid);
				                ///charge account
				                        String insertQuery3 = "adu"	+"INSERT INTO customer_account "
	                                                             	+"(uid,subscription_type,balance,balance_value,active) VALUES "
	                                                             	+"("+ uid +"," + gid + "," + balance +","+ balance_value + ","+ active + ""+")";

                                       sendToServer(insertQuery3);
				                        
								
								///insert to orders
								insertToOrders(gid,balance_value,pid);
								
								
							}
							
							
						}

						public void insertToOrders(int serviceID,double price,int pid)
						{
								
							System.out.println("insert to Orders..............");
							//insert to Orders
							String insertQuery = "adu"	+"INSERT INTO orders "
			                                         	+"(service_id,price_paid,pid) VALUES "
			                                          	+"(" + serviceID + "," + price + "," + pid + ")";
	
							  sendToServer(insertQuery);
							  
						   	System.out.println("Invoice Inserted: ServiceID:"+serviceID+" Price:"+price+ "PID:"+pid);
							   //set the new observer
								SGI.clnt.deleteObservers();
								SGI.clnt.addObserver(prevObserver);
		
		                       //get the last InvoiceId that insert
		                        String searchQuery= "search"  +"SELECT *"
				                                              + " FROM orders AS o, cus_payment_method AS c, user AS u, payment_method AS p "
		                        		                      + " WHERE o.pid=c.pid AND c.uid=u.uid AND p.pid=c.pid"
				                                              + " ORDER BY o.invoice_number DESC "
		                                                      + " LIMIT 1";
		                          sendToServer(searchQuery);
						}

						
						@Override
						public void handleDBRequestSuccess()
						{
							
						}
						
						@Override
						public void handleDBSearchResult(CliMessage dbResult) 
						{	
							//get curr price of service
							ArrayList<HashMap<String, String>> srs = dbResult.getSrs();
							
							if(srs.get(0).get("PRICE")!=null)  	
							{
								//flag
								boolean flag=finSystemModel.getDiscount();
								
								
								System.out.println("price return..............");
							    price=Double.parseDouble(srs.get(0).get("PRICE"));	
							    
							    if (flag)
							    	price=price*0.96;
							    chargeCustomerByService();
							}
							
							//registerd Customer
							if(srs.get(0).get("PID")!=null)
							{
								pid=Integer.parseInt(srs.get(0).get("PID"));
								
								int  uid = finSystemModel.getUID();
									//insert to cus_payment_method
									String insertQuery2 = "adu"	+"INSERT INTO cus_payment_method "
										                    	+"(uid,pid) VALUES "
										                    	+"(" + uid + ","+ pid +")";
									
									
									sendToServer(insertQuery2);
								
								insertToOrders(serviceId,price,pid);
							}
						}

						@Override
						public void handleNullSearchResult() 
						{
							
						}

}
